import React, {Component} from 'react'
import {Form, Input, Button, Select, Card, Spin, message, Icon} from 'antd'
import {connect} from 'react-redux'
import {formItemLayout, mdLayout} from '../../constant/constant-style'
import {withRouter} from 'react-router-dom'
import {TwsReactMarkdownEditor} from 'tws-antd'
import {getSimpleCodingQuiz, editSimpleCodingQuiz} from '../../actions/simple-coding-quiz'
import UrlPattern from 'url-pattern'
import SelectTags from '../common/select-tags'
import {getAllStacks} from '../../actions/stack'
import STATUS from '../../constant/simple-quiz-status'
import {convertContent} from '../../constant/lang-util'
import {FormattedMessage} from 'react-intl'
import {getUploadUrl} from '../../constant/upload-url'

const FormItem = Form.Item
const Option = Select.Option

class EditCodingQuizBody extends Component {
  constructor () {
    super()
    this.state = {
      id: -1,
      repository: '',
      stackId: 0,
      status: 0,
      tags: [],
      description: '',
      stackError: '',
      repositoryError: '',
      isShowSpin: false,
      isShowResult: false,
      referenceAnswer: ''
    }
  }

  componentDidMount () {
    const pattern = new UrlPattern('/simpleCodingQuizzes/:id/editor')

    const urlParams = pattern.match(this.props.location.pathname) || {id: -1}
    this.setState({id: parseInt(urlParams.id, 10)})
    this.props.getSimpleCodingQuiz(urlParams.id)
    this.props.getAllStacks()
  }

  componentWillReceiveProps (nextProps) {
    const {simpleCodingQuiz, form} = nextProps
    if (simpleCodingQuiz === this.props.simpleCodingQuiz) {
      return false
    }
    const tags = simpleCodingQuiz.tags.map(tag => tag.name)
    const {stackId, definitionRepo, description, homeworkName, remark, referenceAnswer, branch} = simpleCodingQuiz

    form.setFieldsValue({tags, stackId, definitionRepo, title: homeworkName, remark, description, referenceAnswer, branch})
    this.setState({id: simpleCodingQuiz.id, tags, status: simpleCodingQuiz.status, jobMessage: simpleCodingQuiz.jobMessage})
  }

  handleSubmit (e) {
    e.preventDefault()
    const {tags, quizGroupId, id} = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values = Object.assign({}, values, {tags, quizGroupId, id})
        this.props.editCodingQuiz(values, () => {
          this.setState({isShowSpin: true, isShowResult: true, status: 0, jobMessage: ''})
          this.loopLogs()
        })
      }
    })
  }

  loopLogs () {
    const {status, id} = this.state
    if (status === STATUS.PENDING) {
      this.props.getSimpleCodingQuiz(id)
      window.setTimeout(() => this.loopLogs(), 1000)
      return
    }

    if (status === STATUS.FAILURE) {
      message.warn(convertContent('出题失败'))
    }
    if (status === STATUS.SUCCESS) {
      message.success(convertContent('出题成功'))
    }
    this.setState({isShowSpin: false})
  }

  render () {
    const {settings, form} = this.props
    const {getFieldDecorator} = form
    const {tags, isShowResult, jobMessage, isShowSpin} = this.state

    return (<Form onSubmit={this.handleSubmit.bind(this)}>
      <p>
        <a onClick={() => window.history.back()}><Icon type='arrow-left' /><FormattedMessage id='返回上一页' /></a>
      </p>
      <FormItem
        label={<FormattedMessage id='名称' />}
        {...formItemLayout}
      >
        {getFieldDecorator('title', {rules: [{required: true, message: <FormattedMessage id='请填写题目名称' />}]})(<Input />)}
      </FormItem>

      <FormItem label={<FormattedMessage id='题目描述' />}{...mdLayout}>
        {getFieldDecorator('description',
          {rules: [{required: true, message: <FormattedMessage id='请填写题目描述' />}]})(
            <TwsReactMarkdownEditor
              action={getUploadUrl(settings.appContextPath)} />)}
      </FormItem>
      <FormItem
        label='stack'
        {...formItemLayout}
      >
        {getFieldDecorator('stackId', {
          rules: [{required: true, message: <FormattedMessage id='请选择技术栈' />}]
        })(
          <Select
            placeholder={<FormattedMessage id='请选择技术栈' />}>
            {this.props.stacks.map(stack => <Option key={stack.id} value={stack.id}>{stack.title}</Option>)}
          </Select>
        )}
      </FormItem>

      <FormItem
        label='repository'
        {...formItemLayout}
      >
        {getFieldDecorator('definitionRepo', {
          rules: [{
            required: true,
            pattern: new RegExp(/^(?:https:\/\/)?(?:github\.com\/)(?:[^ ]+)(?:\/)(?:[^ ]+)$/),
            message: <FormattedMessage id='请填入github地址' />
          }]
        })(
          <Input className='min-width' />
        )}
      </FormItem>
      <FormItem label={<FormattedMessage id='分支' />} {...mdLayout}>
        {getFieldDecorator('branch',
          {rules: [{required: false, message: <FormattedMessage id='分支' />}]})(<Input placeholder='master' />)}
      </FormItem>

      <SelectTags
        addTags={(tags) => this.setState({tags})}
        currentTags={tags} />
      <FormItem
        {...mdLayout}
        label={<FormattedMessage id='参考答案' />}
      >
        {getFieldDecorator('referenceAnswer',
          {rules: [{required: false, message: <FormattedMessage id='请填写参考答案' />}]})(
            <TwsReactMarkdownEditor
              action={getUploadUrl(settings.appContextPath)} />)}
      </FormItem>
      {isShowResult
        ? <Card style={{width: '100%'}}>
          {isShowSpin ? <Spin /> : ''}
          <div>{jobMessage}</div>
        </Card>
        : ''}
      <FormItem
        wrapperCol={{offset: 9}}
      >
        <Button type='primary' htmlType='submit'>
          <FormattedMessage id='修改' />
        </Button>
      </FormItem>
    </Form>)
  }
}

const mapStateToProps = ({simpleCodingQuiz, stackData, settings}) => ({
  settings,
  simpleCodingQuiz,
  stacks: stackData.stacks.content
})

const mapDispatchToProps = dispatch => ({
  getSimpleCodingQuiz: (quizId) => dispatch(getSimpleCodingQuiz(quizId)),
  editCodingQuiz: (quiz, callback) => dispatch(editSimpleCodingQuiz(quiz, callback)),
  getAllStacks: () => dispatch(getAllStacks())
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Form.create()(EditCodingQuizBody)))
